/**
 * 
 */
package valfazz.android.karfinder.activity;

import valfazz.android.karfinder.R;
import valfazz.android.karfinder.database.DatabaseHelper;
import valfazz.android.karfinder.pojo.Song;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

/**
 * @author Val
 *
 */
public class SongViewerActivity extends Activity {
	private static final String TAG = "SongViewerActivity";
	private TextView tvSongId;
	private TextView tvSongTitle;
	private TextView tvSongLyrics;
	private TextView tvSongComposer;
	private TextView tvSongGenre;
	private CheckBox cbSongFavorite;
	private Button btnBack;
	private boolean initialFavorite;
	private DatabaseHelper dbHelper;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_song_viewer);
		
		tvSongId = (TextView)findViewById(R.id.tvSongViewerId);
		tvSongTitle = (TextView)findViewById(R.id.tvSongViewerTitle);
		tvSongLyrics = (TextView)findViewById(R.id.tvSongViewerLyrics);
		tvSongComposer = (TextView)findViewById(R.id.tvSongViewerComposer);
		tvSongGenre = (TextView)findViewById(R.id.tvSongViewerGenre);
		cbSongFavorite = (CheckBox)findViewById(R.id.cbSongViewerFavorite);
		btnBack = (Button)findViewById(R.id.btnSongViewerBack);
		
		btnBack.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				finish();
			}
		});
		
		dbHelper = new DatabaseHelper(SongViewerActivity.this);
		displaySongInfo();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		Log.i(TAG, "onPause");
		Log.i("initialFavorite", (initialFavorite ? "YES" : "NO"));
		Log.i("isFavorite", (cbSongFavorite.isChecked() ? "YES" : "NO"));
		if (initialFavorite != cbSongFavorite.isChecked()) {
			Log.i("set " + tvSongId.getText().toString(), cbSongFavorite.isChecked() + "");
			dbHelper.setFavorite(tvSongId.getText().toString(), cbSongFavorite.isChecked());
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		dbHelper.close();
	}

	/**
	 * @author Val
	 * 
	 */
	private void displaySongInfo() {
		Song song = dbHelper.getSong(this.getIntent().getStringExtra("songId"));

		Log.i("SONG INFO", song.toString());
		tvSongId.setText(song.getId() + "");
		tvSongTitle.setText(song.getTitle());
		tvSongLyrics.setText(song.getLyrics());
		tvSongComposer.setText(song.getComposer());
		tvSongGenre.setText(song.getGenre());
		cbSongFavorite.setChecked(song.getFavorite());
		initialFavorite = cbSongFavorite.isChecked();
	}
}
